#include "datavisualization.h"
#include <QBarCategoryAxis>
#include <QBarSet>
#include <QPieSlice>
#include <QFile>
#include <QTextStream>
#include <QFileInfo>
#include <QDir>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QImage>
#include <QPainter>

// 构造函数
DataVisualization::DataVisualization(QObject *parent) : QObject(parent),
    m_deviceController(nullptr),
    m_samplingManager(nullptr),
    m_auditLogger(nullptr),
    m_flowRateChart(nullptr),
    m_batteryChart(nullptr),
    m_samplingStatsChart(nullptr),
    m_temperatureChart(nullptr),
    m_humidityChart(nullptr),
    m_deviceStatusChart(nullptr),
    m_flowRateSeries(nullptr),
    m_batterySeries(nullptr),
    m_temperatureSeries(nullptr),
    m_humiditySeries(nullptr),
    m_samplingStatsSeries(nullptr),
    m_deviceStatusSeries(nullptr),
    m_timeAxis(nullptr),
    m_valueAxis(nullptr),
    m_updateTimer(nullptr),
    m_updateInterval(5000), // 默认5秒更新一次
    m_timeRangeHours(24),   // 默认显示24小时数据
    m_realTimeEnabled(true)
{
    qDebug() << "DataVisualization constructor started";
    
    // 创建更新定时器
    qDebug() << "Creating update timer...";
    m_updateTimer = new QTimer(this);
    qDebug() << "Update timer created, connecting signal...";
    connect(m_updateTimer, &QTimer::timeout, this, &DataVisualization::onRealTimeUpdate);
    qDebug() << "DataVisualization constructor completed";
}

// 析构函数
DataVisualization::~DataVisualization()
{
    // 保存图表数据
    saveChartData(CHART_FLOW_RATE);
    saveChartData(CHART_BATTERY_LEVEL);
    saveChartData(CHART_TEMPERATURE);
    saveChartData(CHART_HUMIDITY);
    
    // 停止定时器
    if (m_updateTimer && m_updateTimer->isActive()) {
        m_updateTimer->stop();
    }
    
    // 清理图表对象
    delete m_flowRateChart;
    delete m_batteryChart;
    delete m_samplingStatsChart;
    delete m_temperatureChart;
    delete m_humidityChart;
    delete m_deviceStatusChart;
}

// 初始化方法
bool DataVisualization::initialize(DeviceController* deviceController, 
                                  SamplingManager* samplingManager, 
                                  AuditLogger* auditLogger)
{
    if (!deviceController || !samplingManager || !auditLogger) {
        qWarning() << "数据可视化初始化失败：无效的参数";
        return false;
    }
    
    m_deviceController = deviceController;
    m_samplingManager = samplingManager;
    m_auditLogger = auditLogger;
    
    // 连接信号
    connect(m_deviceController, QOverload<int>::of(&DeviceController::flowRateChanged),
            this, &DataVisualization::onDeviceParametersChanged);
    connect(m_deviceController, QOverload<float>::of(&DeviceController::temperatureChanged),
            this, &DataVisualization::onDeviceParametersChanged);
    connect(m_deviceController, QOverload<float>::of(&DeviceController::humidityChanged),
            this, &DataVisualization::onDeviceParametersChanged);
    connect(m_samplingManager, &SamplingManager::taskCompleted,
            this, [this](int taskId, bool success) {
                Q_UNUSED(taskId);
                Q_UNUSED(success);
                this->updateSamplingStats();
            });
    
    // 初始化图表
    initializeCharts();
    
    // 加载历史数据
    loadChartData(CHART_FLOW_RATE);
    loadChartData(CHART_BATTERY_LEVEL);
    loadChartData(CHART_TEMPERATURE);
    loadChartData(CHART_HUMIDITY);
    
    // 创建数据表
    createDataTables();
    
    // 启动定时器
    if (m_realTimeEnabled) {
        m_updateTimer->start(m_updateInterval);
    }
    
    AuditLogger::AuditRecord record;
    record.timestamp = QDateTime::currentDateTime();
    record.userId = "system";
    record.action = AuditLogger::System;
    record.tableName = "DataVisualization";
    record.recordId = "";
    record.oldValue = "";
    record.newValue = "";
    record.description = "数据可视化模块初始化成功";
    m_auditLogger->logEvent(record);
    return true;
}

// 图表获取方法
QChart* DataVisualization::getFlowRateChart()
{
    if (!m_flowRateChart) {
        setupFlowRateChart();
    }
    return m_flowRateChart;
}

QChart* DataVisualization::getBatteryChart()
{
    if (!m_batteryChart) {
        setupBatteryChart();
    }
    return m_batteryChart;
}

QChart* DataVisualization::getSamplingStatsChart()
{
    if (!m_samplingStatsChart) {
        setupSamplingStatsChart();
    }
    return m_samplingStatsChart;
}

QChart* DataVisualization::getTemperatureChart()
{
    if (!m_temperatureChart) {
        setupTemperatureChart();
    }
    return m_temperatureChart;
}

QChart* DataVisualization::getHumidityChart()
{
    if (!m_humidityChart) {
        setupHumidityChart();
    }
    return m_humidityChart;
}

QChart* DataVisualization::getDeviceStatusChart()
{
    if (!m_deviceStatusChart) {
        setupDeviceStatusChart();
    }
    return m_deviceStatusChart;
}

// 数据更新方法
void DataVisualization::updateFlowRateData()
{
    if (!m_deviceController) return;
    
    // 获取当前流量
    double flowRate = m_deviceController->getFlowRate();
    QDateTime now = QDateTime::currentDateTime();
    
    // 添加数据点
    addDataPoint(CHART_FLOW_RATE, flowRate, now);
    
    // 更新图表
    updateChartSeries(CHART_FLOW_RATE);
    
    // 移除旧数据点
    removeOldDataPoints(CHART_FLOW_RATE, m_timeRangeHours);
    
    emit flowRateChartChanged();
    emit chartDataUpdated(CHART_FLOW_RATE);
}

void DataVisualization::updateBatteryData()
{
    if (!m_deviceController) return;
    
    // 获取当前电池电量
    double batteryLevel = m_deviceController->getBatteryLevel();
    QDateTime now = QDateTime::currentDateTime();
    
    // 添加数据点
    addDataPoint(CHART_BATTERY_LEVEL, batteryLevel, now);
    
    // 更新图表
    updateChartSeries(CHART_BATTERY_LEVEL);
    
    // 移除旧数据点
    removeOldDataPoints(CHART_BATTERY_LEVEL, m_timeRangeHours);
    
    emit batteryChartChanged();
    emit chartDataUpdated(CHART_BATTERY_LEVEL);
}

void DataVisualization::updateSamplingStats()
{
    if (!m_samplingManager) return;
    
    // 计算采样统计数据
    SamplingStatistics stats = calculateSamplingStatistics(7); // 默认显示7天的统计
    
    // 更新采样统计图表
    if (m_samplingStatsChart && m_samplingStatsSeries) {
        // 清除现有数据
        QList<QBarSet*> barSets = m_samplingStatsSeries->barSets();
        for (QBarSet* set : barSets) {
            m_samplingStatsSeries->remove(set);
        }
        
        // 创建新的数据集
        QBarSet *successSet = new QBarSet("成功");
        QBarSet *failedSet = new QBarSet("失败");
        
        // 设置数据
        *successSet << stats.successful_samples;
        *failedSet << stats.failed_samples;
        
        // 设置颜色
        successSet->setColor(QColor(0, 128, 0)); // 绿色
        failedSet->setColor(QColor(255, 0, 0));  // 红色
        
        // 添加到系列
        m_samplingStatsSeries->append(successSet);
        m_samplingStatsSeries->append(failedSet);
    }
    
    emit samplingStatsChartChanged();
    emit chartDataUpdated(CHART_SAMPLING_STATS);
    emit statisticsUpdated();
}

void DataVisualization::updateAllCharts()
{
    updateFlowRateData();
    updateBatteryData();
    updateSamplingStats();
    
    // 更新温度和湿度
    if (m_deviceController) {
        double temperature = m_deviceController->getTemperature();
        double humidity = m_deviceController->getHumidity();
        QDateTime now = QDateTime::currentDateTime();
        
        addDataPoint(CHART_TEMPERATURE, temperature, now);
        addDataPoint(CHART_HUMIDITY, humidity, now);
        
        updateChartSeries(CHART_TEMPERATURE);
        updateChartSeries(CHART_HUMIDITY);
        
        removeOldDataPoints(CHART_TEMPERATURE, m_timeRangeHours);
        removeOldDataPoints(CHART_HUMIDITY, m_timeRangeHours);
        
        emit chartDataUpdated(CHART_TEMPERATURE);
        emit chartDataUpdated(CHART_HUMIDITY);
    }
    
    // 更新设备状态
    if (m_deviceController && m_deviceStatusSeries) {
        int status = m_deviceController->getDeviceStatus();
        QDateTime now = QDateTime::currentDateTime();
        
        // 添加设备状态数据点
        DataPoint point;
        point.timestamp = now;
        point.value = status;
        point.category = status;
        point.label = QString("状态 %1").arg(status);
        
        // 更新设备状态图表
        // 这里简化处理，实际应用中可能需要更复杂的逻辑
        emit chartDataUpdated(CHART_DEVICE_STATUS);
    }
}

// 历史数据查询
QVariantList DataVisualization::getFlowRateHistory(int hours) const
{
    QVariantList result;
    QDateTime cutoff = QDateTime::currentDateTime().addSecs(-hours * 3600);
    
    for (const DataPoint& point : m_flowRateData) {
        if (point.timestamp >= cutoff) {
            result.append(dataPointToVariant(point));
        }
    }
    
    return result;
}

QVariantList DataVisualization::getBatteryHistory(int hours) const
{
    QVariantList result;
    QDateTime cutoff = QDateTime::currentDateTime().addSecs(-hours * 3600);
    
    for (const DataPoint& point : m_batteryData) {
        if (point.timestamp >= cutoff) {
            result.append(dataPointToVariant(point));
        }
    }
    
    return result;
}

QVariantList DataVisualization::getTemperatureHistory(int hours) const
{
    QVariantList result;
    QDateTime cutoff = QDateTime::currentDateTime().addSecs(-hours * 3600);
    
    for (const DataPoint& point : m_temperatureData) {
        if (point.timestamp >= cutoff) {
            result.append(dataPointToVariant(point));
        }
    }
    
    return result;
}

QVariantList DataVisualization::getHumidityHistory(int hours) const
{
    QVariantList result;
    QDateTime cutoff = QDateTime::currentDateTime().addSecs(-hours * 3600);
    
    for (const DataPoint& point : m_humidityData) {
        if (point.timestamp >= cutoff) {
            result.append(dataPointToVariant(point));
        }
    }
    
    return result;
}

// 统计数据获取
QVariant DataVisualization::getSamplingStatistics(int days) const
{
    SamplingStatistics stats = calculateSamplingStatistics(days);
    return samplingStatisticsToVariant(stats);
}

QVariant DataVisualization::getDashboardData() const
{
    QVariantMap result;
    
    if (m_deviceController && m_samplingManager) {
        // 设备状态信息
        result["deviceStatus"] = m_deviceController->getDeviceStatus();
        result["batteryLevel"] = m_deviceController->getBatteryLevel();
        result["flowRate"] = m_deviceController->getFlowRate();
        result["temperature"] = m_deviceController->getTemperature();
        result["humidity"] = m_deviceController->getHumidity();
        
        // 采样统计信息
        SamplingStatistics stats = calculateSamplingStatistics(1); // 今日统计
        result["todaySamples"] = stats.total_samples;
        result["successfulSamples"] = stats.successful_samples;
        result["failedSamples"] = stats.failed_samples;
        result["avgFlowRate"] = stats.avg_flow_rate;
        result["totalVolume"] = stats.total_volume;
        
        // 最后采样信息
        if (!stats.last_sample.isNull()) {
            result["lastSampleTime"] = stats.last_sample.toString("yyyy-MM-dd hh:mm:ss");
        } else {
            result["lastSampleTime"] = "无";
        }
        
        // 设备连接状态
        result["deviceConnected"] = (m_deviceController->getDeviceStatus() != DEVICE_ERROR);
        result["deviceName"] = "细菌采样器";
        result["deviceId"] = "BSS-001";
    }
    
    return result;
}

QVariantList DataVisualization::getDeviceStatusHistory(int hours) const
{
    // 这里简化实现，实际应用中可能需要从数据库或其他存储中获取历史状态
    QVariantList result;
    
    // 示例数据
    QDateTime now = QDateTime::currentDateTime();
    for (int i = 0; i < 10; i++) {
        QVariantMap entry;
        entry["timestamp"] = now.addSecs(-i * 3600).toString("yyyy-MM-dd hh:mm:ss");
        entry["status"] = i % 3; // 示例状态值
        entry["description"] = QString("状态 %1").arg(i % 3);
        result.append(entry);
    }
    
    return result;
}

// 图表配置
void DataVisualization::setChartTimeRange(ChartType chartType, int hours)
{
    if (hours <= 0) return;
    
    m_timeRangeHours = hours;
    
    // 更新图表显示范围
    QDateTime now = QDateTime::currentDateTime();
    QDateTime startTime = now.addSecs(-hours * 3600);
    
    QChart* chart = nullptr;
    switch (chartType) {
        case CHART_FLOW_RATE:
            chart = m_flowRateChart;
            break;
        case CHART_BATTERY_LEVEL:
            chart = m_batteryChart;
            break;
        case CHART_TEMPERATURE:
            chart = m_temperatureChart;
            break;
        case CHART_HUMIDITY:
            chart = m_humidityChart;
            break;
        default:
            return;
    }
    
    if (chart) {
        updateChartAxes(chart, startTime, now);
        
        // 移除超出范围的数据点
        removeOldDataPoints(chartType, hours);
        
        // 更新图表
        updateChartSeries(chartType);
        
        // 发送信号
        emit chartDataUpdated(chartType);
    }
}

void DataVisualization::setChartUpdateInterval(int seconds)
{
    if (seconds <= 0) return;
    
    m_updateInterval = seconds * 1000; // 转换为毫秒
    
    if (m_updateTimer && m_realTimeEnabled) {
        m_updateTimer->stop();
        m_updateTimer->start(m_updateInterval);
    }
}

void DataVisualization::enableRealTimeUpdate(bool enabled)
{
    m_realTimeEnabled = enabled;
    
    if (m_updateTimer) {
        if (enabled) {
            m_updateTimer->start(m_updateInterval);
        } else {
            m_updateTimer->stop();
        }
    }
}

// 数据导出
bool DataVisualization::exportChartData(ChartType chartType, const QString& filePath) const
{
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件进行写入:" << filePath;
        return false;
    }
    
    QTextStream out(&file);
    out << "时间戳,数值,标签,分类\n";
    
    const QList<DataPoint>* dataPoints = nullptr;
    
    switch (chartType) {
        case CHART_FLOW_RATE:
            dataPoints = &m_flowRateData;
            break;
        case CHART_BATTERY_LEVEL:
            dataPoints = &m_batteryData;
            break;
        case CHART_TEMPERATURE:
            dataPoints = &m_temperatureData;
            break;
        case CHART_HUMIDITY:
            dataPoints = &m_humidityData;
            break;
        default:
            file.close();
            return false;
    }
    
    for (const DataPoint& point : *dataPoints) {
        out << point.timestamp.toString("yyyy-MM-dd hh:mm:ss") << ","
            << point.value << ","
            << point.label << ","
            << point.category << "\n";
    }
    
    file.close();
    return true;
}

bool DataVisualization::exportChartImage(ChartType chartType, const QString& filePath) const
{
    QChart* chart = nullptr;
    
    switch (chartType) {
        case CHART_FLOW_RATE:
            chart = m_flowRateChart;
            break;
        case CHART_BATTERY_LEVEL:
            chart = m_batteryChart;
            break;
        case CHART_SAMPLING_STATS:
            chart = m_samplingStatsChart;
            break;
        case CHART_TEMPERATURE:
            chart = m_temperatureChart;
            break;
        case CHART_HUMIDITY:
            chart = m_humidityChart;
            break;
        case CHART_DEVICE_STATUS:
            chart = m_deviceStatusChart;
            break;
        default:
            return false;
    }
    
    if (!chart) return false;
    
    // 创建图像
    QPixmap pixmap(800, 600);
    pixmap.fill(Qt::white);
    
    QPainter painter(&pixmap);
    chart->paint(&painter, nullptr, nullptr);
    
    return pixmap.save(filePath);
}

// 图表样式设置
void DataVisualization::setChartTheme(int theme)
{
    if (m_flowRateChart) applyChartTheme(m_flowRateChart, theme);
    if (m_batteryChart) applyChartTheme(m_batteryChart, theme);
    if (m_samplingStatsChart) applyChartTheme(m_samplingStatsChart, theme);
    if (m_temperatureChart) applyChartTheme(m_temperatureChart, theme);
    if (m_humidityChart) applyChartTheme(m_humidityChart, theme);
    if (m_deviceStatusChart) applyChartTheme(m_deviceStatusChart, theme);
    
    // 发送信号
    emit flowRateChartChanged();
    emit batteryChartChanged();
    emit samplingStatsChartChanged();
    emit chartDataUpdated(CHART_FLOW_RATE);
    emit chartDataUpdated(CHART_BATTERY_LEVEL);
    emit chartDataUpdated(CHART_SAMPLING_STATS);
    emit chartDataUpdated(CHART_TEMPERATURE);
    emit chartDataUpdated(CHART_HUMIDITY);
    emit chartDataUpdated(CHART_DEVICE_STATUS);
}

void DataVisualization::setChartColors(const QVariantList& colors)
{
    if (m_flowRateChart) ::DataVisualization::setChartColors(m_flowRateChart, colors);
    if (m_batteryChart) ::DataVisualization::setChartColors(m_batteryChart, colors);
    if (m_samplingStatsChart) ::DataVisualization::setChartColors(m_samplingStatsChart, colors);
    if (m_temperatureChart) ::DataVisualization::setChartColors(m_temperatureChart, colors);
    if (m_humidityChart) ::DataVisualization::setChartColors(m_humidityChart, colors);
    if (m_deviceStatusChart) ::DataVisualization::setChartColors(m_deviceStatusChart, colors);
    
    // 发送信号
    emit flowRateChartChanged();
    emit batteryChartChanged();
    emit samplingStatsChartChanged();
    emit chartDataUpdated(CHART_FLOW_RATE);
    emit chartDataUpdated(CHART_BATTERY_LEVEL);
    emit chartDataUpdated(CHART_SAMPLING_STATS);
    emit chartDataUpdated(CHART_TEMPERATURE);
    emit chartDataUpdated(CHART_HUMIDITY);
    emit chartDataUpdated(CHART_DEVICE_STATUS);
}

void DataVisualization::setChartTitle(ChartType chartType, const QString& title)
{
    QChart* chart = nullptr;
    
    switch (chartType) {
        case CHART_FLOW_RATE:
            chart = m_flowRateChart;
            break;
        case CHART_BATTERY_LEVEL:
            chart = m_batteryChart;
            break;
        case CHART_SAMPLING_STATS:
            chart = m_samplingStatsChart;
            break;
        case CHART_TEMPERATURE:
            chart = m_temperatureChart;
            break;
        case CHART_HUMIDITY:
            chart = m_humidityChart;
            break;
        case CHART_DEVICE_STATUS:
            chart = m_deviceStatusChart;
            break;
        default:
            return;
    }
    
    if (chart) {
        chart->setTitle(title);
        emit chartDataUpdated(chartType);
    }
}

// 私有槽函数
void DataVisualization::onRealTimeUpdate()
{
    updateAllCharts();
}

void DataVisualization::onDeviceParametersChanged()
{
    // 设备参数变化时更新相关图表
    updateFlowRateData();
    updateBatteryData();
    
    // 更新温度和湿度
    if (m_deviceController) {
        double temperature = m_deviceController->getTemperature();
        double humidity = m_deviceController->getHumidity();
        QDateTime now = QDateTime::currentDateTime();
        
        addDataPoint(CHART_TEMPERATURE, temperature, now);
        addDataPoint(CHART_HUMIDITY, humidity, now);
        
        updateChartSeries(CHART_TEMPERATURE);
        updateChartSeries(CHART_HUMIDITY);
        
        emit chartDataUpdated(CHART_TEMPERATURE);
        emit chartDataUpdated(CHART_HUMIDITY);
    }
}

void DataVisualization::onSamplingCompleted()
{
    // 采样完成时更新统计图表
    updateSamplingStats();
}

// 私有方法
void DataVisualization::initializeCharts()
{
    setupFlowRateChart();
    setupBatteryChart();
    setupSamplingStatsChart();
    setupTemperatureChart();
    setupHumidityChart();
    setupDeviceStatusChart();
}

void DataVisualization::setupFlowRateChart()
{
    if (m_flowRateChart) return;
    
    m_flowRateChart = new QChart();
    m_flowRateChart->setTitle("流量监测");
    
    m_flowRateSeries = new QLineSeries();
    m_flowRateSeries->setName("流量 (L/min)");
    
    m_flowRateChart->addSeries(m_flowRateSeries);
    
    // 创建坐标轴
    QDateTimeAxis *axisX = new QDateTimeAxis;
    axisX->setTitleText("时间");
    axisX->setFormat("hh:mm:ss");
    axisX->setTickCount(5);
    
    QValueAxis *axisY = new QValueAxis;
    axisY->setTitleText("流量 (L/min)");
    axisY->setLabelFormat("%.2f");
    axisY->setTickCount(5);
    
    m_flowRateChart->addAxis(axisX, Qt::AlignBottom);
    m_flowRateChart->addAxis(axisY, Qt::AlignLeft);
    
    m_flowRateSeries->attachAxis(axisX);
    m_flowRateSeries->attachAxis(axisY);
    
    // 设置图表外观
    configureChartAppearance(m_flowRateChart);
}

void DataVisualization::setupBatteryChart()
{
    if (m_batteryChart) return;
    
    m_batteryChart = new QChart();
    m_batteryChart->setTitle("电池电量");
    
    m_batterySeries = new QLineSeries();
    m_batterySeries->setName("电量 (%)");
    
    m_batteryChart->addSeries(m_batterySeries);
    
    // 创建坐标轴
    QDateTimeAxis *axisX = new QDateTimeAxis;
    axisX->setTitleText("时间");
    axisX->setFormat("hh:mm:ss");
    axisX->setTickCount(5);
    
    QValueAxis *axisY = new QValueAxis;
    axisY->setTitleText("电量 (%)");
    axisY->setLabelFormat("%.1f");
    axisY->setRange(0, 100);
    axisY->setTickCount(5);
    
    m_batteryChart->addAxis(axisX, Qt::AlignBottom);
    m_batteryChart->addAxis(axisY, Qt::AlignLeft);
    
    m_batterySeries->attachAxis(axisX);
    m_batterySeries->attachAxis(axisY);
    
    // 设置图表外观
    configureChartAppearance(m_batteryChart);
}

void DataVisualization::setupSamplingStatsChart()
{
    if (m_samplingStatsChart) return;
    
    m_samplingStatsChart = new QChart();
    m_samplingStatsChart->setTitle("采样统计");
    
    m_samplingStatsSeries = new QBarSeries();
    
    // 创建示例数据
    QBarSet *successSet = new QBarSet("成功");
    QBarSet *failedSet = new QBarSet("失败");
    
    *successSet << 0;
    *failedSet << 0;
    
    m_samplingStatsSeries->append(successSet);
    m_samplingStatsSeries->append(failedSet);
    
    m_samplingStatsChart->addSeries(m_samplingStatsSeries);
    
    // 创建坐标轴
    QBarCategoryAxis *axisX = new QBarCategoryAxis();
    axisX->append("采样结果");
    
    QValueAxis *axisY = new QValueAxis();
    axisY->setTitleText("数量");
    axisY->setLabelFormat("%d");
    axisY->setRange(0, 10);
    
    m_samplingStatsChart->addAxis(axisX, Qt::AlignBottom);
    m_samplingStatsChart->addAxis(axisY, Qt::AlignLeft);
    
    m_samplingStatsSeries->attachAxis(axisX);
    m_samplingStatsSeries->attachAxis(axisY);
    
    // 设置图表外观
    configureChartAppearance(m_samplingStatsChart);
}

void DataVisualization::setupTemperatureChart()
{
    if (m_temperatureChart) return;
    
    m_temperatureChart = new QChart();
    m_temperatureChart->setTitle("温度监测");
    
    m_temperatureSeries = new QLineSeries();
    m_temperatureSeries->setName("温度 (°C)");
    
    m_temperatureChart->addSeries(m_temperatureSeries);
    
    // 创建坐标轴
    QDateTimeAxis *axisX = new QDateTimeAxis;
    axisX->setTitleText("时间");
    axisX->setFormat("hh:mm:ss");
    axisX->setTickCount(5);
    
    QValueAxis *axisY = new QValueAxis;
    axisY->setTitleText("温度 (°C)");
    axisY->setLabelFormat("%.1f");
    axisY->setTickCount(5);
    
    m_temperatureChart->addAxis(axisX, Qt::AlignBottom);
    m_temperatureChart->addAxis(axisY, Qt::AlignLeft);
    
    m_temperatureSeries->attachAxis(axisX);
    m_temperatureSeries->attachAxis(axisY);
    
    // 设置图表外观
    configureChartAppearance(m_temperatureChart);
}

void DataVisualization::setupHumidityChart()
{
    if (m_humidityChart) return;
    
    m_humidityChart = new QChart();
    m_humidityChart->setTitle("湿度监测");
    
    m_humiditySeries = new QLineSeries();
    m_humiditySeries->setName("湿度 (%)");
    
    m_humidityChart->addSeries(m_humiditySeries);
    
    // 创建坐标轴
    QDateTimeAxis *axisX = new QDateTimeAxis;
    axisX->setTitleText("时间");
    axisX->setFormat("hh:mm:ss");
    axisX->setTickCount(5);
    
    QValueAxis *axisY = new QValueAxis;
    axisY->setTitleText("湿度 (%)");
    axisY->setLabelFormat("%.1f");
    axisY->setRange(0, 100);
    axisY->setTickCount(5);
    
    m_humidityChart->addAxis(axisX, Qt::AlignBottom);
    m_humidityChart->addAxis(axisY, Qt::AlignLeft);
    
    m_humiditySeries->attachAxis(axisX);
    m_humiditySeries->attachAxis(axisY);
    
    // 设置图表外观
    configureChartAppearance(m_humidityChart);
}

void DataVisualization::setupDeviceStatusChart()
{
    if (m_deviceStatusChart) return;
    
    m_deviceStatusChart = new QChart();
    m_deviceStatusChart->setTitle("设备状态");
    
    m_deviceStatusSeries = new QPieSeries();
    
    // 创建示例数据
    m_deviceStatusSeries->append("正常", 80);
    m_deviceStatusSeries->append("警告", 15);
    m_deviceStatusSeries->append("错误", 5);
    
    // 设置颜色
    QPieSlice *slice1 = m_deviceStatusSeries->slices().at(0);
    slice1->setColor(QColor(0, 128, 0)); // 绿色
    slice1->setLabelVisible(true);
    
    QPieSlice *slice2 = m_deviceStatusSeries->slices().at(1);
    slice2->setColor(QColor(255, 165, 0)); // 橙色
    slice2->setLabelVisible(true);
    
    QPieSlice *slice3 = m_deviceStatusSeries->slices().at(2);
    slice3->setColor(QColor(255, 0, 0)); // 红色
    slice3->setLabelVisible(true);
    
    m_deviceStatusChart->addSeries(m_deviceStatusSeries);
    
    // 设置图表外观
    configureChartAppearance(m_deviceStatusChart);
}

void DataVisualization::addDataPoint(ChartType chartType, double value, const QDateTime& timestamp)
{
    DataPoint point;
    point.timestamp = timestamp;
    point.value = value;
    point.category = 0; // 默认分类
    
    switch (chartType) {
        case CHART_FLOW_RATE:
            point.label = QString("流量: %1 L/min").arg(value, 0, 'f', 2);
            m_flowRateData.append(point);
            break;
        case CHART_BATTERY_LEVEL:
            point.label = QString("电量: %1%").arg(value, 0, 'f', 1);
            m_batteryData.append(point);
            break;
        case CHART_TEMPERATURE:
            point.label = QString("温度: %1°C").arg(value, 0, 'f', 1);
            m_temperatureData.append(point);
            break;
        case CHART_HUMIDITY:
            point.label = QString("湿度: %1%").arg(value, 0, 'f', 1);
            m_humidityData.append(point);
            break;
        default:
            break;
    }
}

void DataVisualization::removeOldDataPoints(ChartType chartType, int maxHours)
{
    QDateTime cutoff = QDateTime::currentDateTime().addSecs(-maxHours * 3600);
    
    switch (chartType) {
        case CHART_FLOW_RATE:
            while (!m_flowRateData.isEmpty() && m_flowRateData.first().timestamp < cutoff) {
                m_flowRateData.removeFirst();
            }
            break;
        case CHART_BATTERY_LEVEL:
            while (!m_batteryData.isEmpty() && m_batteryData.first().timestamp < cutoff) {
                m_batteryData.removeFirst();
            }
            break;
        case CHART_TEMPERATURE:
            while (!m_temperatureData.isEmpty() && m_temperatureData.first().timestamp < cutoff) {
                m_temperatureData.removeFirst();
            }
            break;
        case CHART_HUMIDITY:
            while (!m_humidityData.isEmpty() && m_humidityData.first().timestamp < cutoff) {
                m_humidityData.removeFirst();
            }
            break;
        default:
            break;
    }
}

void DataVisualization::updateChartSeries(ChartType chartType)
{
    switch (chartType) {
        case CHART_FLOW_RATE:
            if (m_flowRateSeries) {
                m_flowRateSeries->clear();
                for (const DataPoint& point : m_flowRateData) {
                    m_flowRateSeries->append(point.timestamp.toMSecsSinceEpoch(), point.value);
                }
                
                // 更新坐标轴
                if (!m_flowRateData.isEmpty() && m_flowRateChart) {
                    QDateTime minTime = m_flowRateData.first().timestamp;
                    QDateTime maxTime = m_flowRateData.last().timestamp;
                    updateChartAxes(m_flowRateChart, minTime, maxTime);
                }
            }
            break;
        case CHART_BATTERY_LEVEL:
            if (m_batterySeries) {
                m_batterySeries->clear();
                for (const DataPoint& point : m_batteryData) {
                    m_batterySeries->append(point.timestamp.toMSecsSinceEpoch(), point.value);
                }
                
                // 更新坐标轴
                if (!m_batteryData.isEmpty() && m_batteryChart) {
                    QDateTime minTime = m_batteryData.first().timestamp;
                    QDateTime maxTime = m_batteryData.last().timestamp;
                    updateChartAxes(m_batteryChart, minTime, maxTime);
                }
            }
            break;
        case CHART_TEMPERATURE:
            if (m_temperatureSeries) {
                m_temperatureSeries->clear();
                for (const DataPoint& point : m_temperatureData) {
                    m_temperatureSeries->append(point.timestamp.toMSecsSinceEpoch(), point.value);
                }
                
                // 更新坐标轴
                if (!m_temperatureData.isEmpty() && m_temperatureChart) {
                    QDateTime minTime = m_temperatureData.first().timestamp;
                    QDateTime maxTime = m_temperatureData.last().timestamp;
                    updateChartAxes(m_temperatureChart, minTime, maxTime);
                }
            }
            break;
        case CHART_HUMIDITY:
            if (m_humiditySeries) {
                m_humiditySeries->clear();
                for (const DataPoint& point : m_humidityData) {
                    m_humiditySeries->append(point.timestamp.toMSecsSinceEpoch(), point.value);
                }
                
                // 更新坐标轴
                if (!m_humidityData.isEmpty() && m_humidityChart) {
                    QDateTime minTime = m_humidityData.first().timestamp;
                    QDateTime maxTime = m_humidityData.last().timestamp;
                    updateChartAxes(m_humidityChart, minTime, maxTime);
                }
            }
            break;
        default:
            break;
    }
}

void DataVisualization::updateChartAxes(QChart* chart, const QDateTime& minTime, const QDateTime& maxTime)
{
    if (!chart) return;
    
    // 获取X轴
    QDateTimeAxis* axisX = nullptr;
    foreach (QAbstractAxis* axis, chart->axes(Qt::Horizontal)) {
        axisX = qobject_cast<QDateTimeAxis*>(axis);
        if (axisX) break;
    }
    
    if (axisX) {
        axisX->setRange(minTime, maxTime);
    }
    
    // 获取Y轴
    QValueAxis* axisY = nullptr;
    foreach (QAbstractAxis* axis, chart->axes(Qt::Vertical)) {
        axisY = qobject_cast<QValueAxis*>(axis);
        if (axisY) break;
    }
    
    if (axisY) {
        // 根据图表类型设置Y轴范围
        if (chart == m_batteryChart || chart == m_humidityChart) {
            axisY->setRange(0, 100);
        } else if (chart == m_flowRateChart) {
            // 查找最大值和最小值
            double minValue = 0;
            double maxValue = 10;
            
            if (chart == m_flowRateChart && !m_flowRateData.isEmpty()) {
                minValue = m_flowRateData.first().value;
                maxValue = m_flowRateData.first().value;
                
                for (const DataPoint& point : m_flowRateData) {
                    minValue = qMin(minValue, point.value);
                    maxValue = qMax(maxValue, point.value);
                }
                
                // 添加一些边距
                double range = maxValue - minValue;
                minValue = qMax(0.0, minValue - range * 0.1);
                maxValue = maxValue + range * 0.1;
            }
            
            axisY->setRange(minValue, maxValue);
        } else if (chart == m_temperatureChart) {
            // 查找最大值和最小值
            double minValue = 0;
            double maxValue = 40;
            
            if (!m_temperatureData.isEmpty()) {
                minValue = m_temperatureData.first().value;
                maxValue = m_temperatureData.first().value;
                
                for (const DataPoint& point : m_temperatureData) {
                    minValue = qMin(minValue, point.value);
                    maxValue = qMax(maxValue, point.value);
                }
                
                // 添加一些边距
                double range = maxValue - minValue;
                minValue = minValue - range * 0.1;
                maxValue = maxValue + range * 0.1;
            }
            
            axisY->setRange(minValue, maxValue);
        }
    }
}

// 数据处理方法
SamplingStatistics DataVisualization::calculateSamplingStatistics(int days) const
{
    SamplingStatistics stats;
    stats.total_samples = 0;
    stats.successful_samples = 0;
    stats.failed_samples = 0;
    stats.avg_flow_rate = 0.0;
    stats.total_volume = 0.0;
    stats.total_time = 0;
    stats.last_sample = QDateTime();
    
    if (!m_samplingManager) return stats;
    
    // 获取采样记录 - 简化实现，从设备控制器获取历史记录
    QList<QVariant> historyVariants = m_deviceController->getSamplingHistory();
    
    if (historyVariants.isEmpty()) return stats;
    
    // 计算统计数据
    stats.total_samples = historyVariants.size();
    double totalFlowRate = 0.0;
    
    for (const QVariant& variant : historyVariants) {
        QVariantMap recordMap = variant.toMap();
        QDateTime recordTime = QDateTime::fromString(recordMap["start_time"].toString(), Qt::ISODate);
        
        // 检查是否在时间范围内
        if (recordTime >= QDateTime::currentDateTime().addDays(-days)) {
            if (recordMap["status"].toInt() == DEVICE_IDLE) {
                stats.successful_samples++;
            } else {
                stats.failed_samples++;
            }
            
            totalFlowRate += recordMap["actual_volume"].toInt() / qMax(1, recordMap["actual_time"].toInt());
            stats.total_volume += recordMap["actual_volume"].toDouble();
            stats.total_time += recordMap["actual_time"].toInt();
            
            if (stats.last_sample.isNull() || recordTime > stats.last_sample) {
                stats.last_sample = recordTime;
            }
        }
    }
    
    if (stats.total_samples > 0) {
        stats.avg_flow_rate = totalFlowRate / stats.total_samples;
    }
    
    return stats;
}

QVariantMap DataVisualization::dataPointToVariant(const DataPoint& point) const
{
    QVariantMap result;
    result["timestamp"] = point.timestamp.toString("yyyy-MM-dd hh:mm:ss");
    result["value"] = point.value;
    result["label"] = point.label;
    result["category"] = point.category;
    return result;
}

QVariantMap DataVisualization::samplingStatisticsToVariant(const SamplingStatistics& stats) const
{
    QVariantMap result;
    result["total_samples"] = stats.total_samples;
    result["successful_samples"] = stats.successful_samples;
    result["failed_samples"] = stats.failed_samples;
    result["avg_flow_rate"] = stats.avg_flow_rate;
    result["total_volume"] = stats.total_volume;
    result["total_time"] = stats.total_time;
    
    if (!stats.last_sample.isNull()) {
        result["last_sample"] = stats.last_sample.toString("yyyy-MM-dd hh:mm:ss");
    } else {
        result["last_sample"] = "";
    }
    
    return result;
}

// 图表样式方法
void DataVisualization::applyChartTheme(QChart* chart, int theme)
{
    if (!chart) return;
    
    switch (theme) {
        case 0: // 浅色主题
            chart->setTheme(QChart::ChartThemeLight);
            break;
        case 1: // 深色主题
            chart->setTheme(QChart::ChartThemeDark);
            break;
        case 2: // 蓝色主题
            chart->setTheme(QChart::ChartThemeBlueIcy);
            break;
        case 3: // 棕色主题
            chart->setTheme(QChart::ChartThemeBrownSand);
            break;
        case 4: // 自然主题
            chart->setTheme(QChart::ChartThemeQt);
            break;
        case 5: // 高对比度主题
            chart->setTheme(QChart::ChartThemeHighContrast);
            break;
        default:
            chart->setTheme(QChart::ChartThemeLight);
            break;
    }
}

void DataVisualization::setChartColors(QChart* chart, const QVariantList& colors)
{
    if (!chart) return;
    
    // 获取图表中的所有系列
    QList<QAbstractSeries*> seriesList = chart->series();
    
    for (int i = 0; i < seriesList.size() && i < colors.size(); ++i) {
        QAbstractSeries* series = seriesList.at(i);
        QColor color = colors.at(i).value<QColor>();
        
        // 根据系列类型设置颜色
        if (QLineSeries* lineSeries = qobject_cast<QLineSeries*>(series)) {
            QPen pen = lineSeries->pen();
            pen.setColor(color);
            lineSeries->setPen(pen);
        } else if (QBarSeries* barSeries = qobject_cast<QBarSeries*>(series)) {
            QList<QBarSet*> barSets = barSeries->barSets();
            for (int j = 0; j < barSets.size() && j < colors.size() - i; ++j) {
                QBarSet* barSet = barSets.at(j);
                barSet->setColor(colors.at(i + j).value<QColor>());
            }
        } else if (QPieSeries* pieSeries = qobject_cast<QPieSeries*>(series)) {
            QList<QPieSlice*> slices = pieSeries->slices();
            for (int j = 0; j < slices.size() && j < colors.size() - i; ++j) {
                QPieSlice* slice = slices.at(j);
                slice->setColor(colors.at(i + j).value<QColor>());
            }
        }
    }
}

void DataVisualization::configureChartAppearance(QChart* chart)
{
    if (!chart) return;
    
    chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);
    
    // 设置字体
    QFont font = chart->titleFont();
    font.setBold(true);
    font.setPointSize(12);
    chart->setTitleFont(font);
    
    // 设置边距
    chart->setMargins(QMargins(10, 10, 10, 10));
    
    // 设置背景
    chart->setBackgroundBrush(QBrush(QColor(240, 240, 240)));
    chart->setBackgroundPen(QPen(QColor(200, 200, 200)));
    
    // 设置绘图区域
    chart->setPlotAreaBackgroundBrush(QBrush(QColor(255, 255, 255)));
    chart->setPlotAreaBackgroundVisible(true);
}

// 数据持久化
bool DataVisualization::saveChartData(ChartType chartType) const
{
    QString fileName;
    const QList<DataPoint>* dataPoints = nullptr;
    
    switch (chartType) {
        case CHART_FLOW_RATE:
            fileName = "flowrate_data.csv";
            dataPoints = &m_flowRateData;
            break;
        case CHART_BATTERY_LEVEL:
            fileName = "battery_data.csv";
            dataPoints = &m_batteryData;
            break;
        case CHART_TEMPERATURE:
            fileName = "temperature_data.csv";
            dataPoints = &m_temperatureData;
            break;
        case CHART_HUMIDITY:
            fileName = "humidity_data.csv";
            dataPoints = &m_humidityData;
            break;
        default:
            return false;
    }
    
    // 创建数据目录
    QDir dir;
    if (!dir.exists("data")) {
        dir.mkdir("data");
    }
    
    QString filePath = "data/" + fileName;
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件进行写入:" << filePath;
        return false;
    }
    
    QTextStream out(&file);
    out << "timestamp,value,label,category\n";
    
    for (const DataPoint& point : *dataPoints) {
        out << point.timestamp.toString("yyyy-MM-dd hh:mm:ss") << ","
            << point.value << ","
            << point.label << ","
            << point.category << "\n";
    }
    
    file.close();
    return true;
}

bool DataVisualization::loadChartData(ChartType chartType)
{
    QString fileName;
    QList<DataPoint>* dataPoints = nullptr;
    
    switch (chartType) {
        case CHART_FLOW_RATE:
            fileName = "flowrate_data.csv";
            dataPoints = &m_flowRateData;
            break;
        case CHART_BATTERY_LEVEL:
            fileName = "battery_data.csv";
            dataPoints = &m_batteryData;
            break;
        case CHART_TEMPERATURE:
            fileName = "temperature_data.csv";
            dataPoints = &m_temperatureData;
            break;
        case CHART_HUMIDITY:
            fileName = "humidity_data.csv";
            dataPoints = &m_humidityData;
            break;
        default:
            return false;
    }
    
    QString filePath = "data/" + fileName;
    QFile file(filePath);
    if (!file.exists() || !file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }
    
    QTextStream in(&file);
    
    // 跳过标题行
    if (!in.atEnd()) {
        in.readLine();
    }
    
    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(',');
        
        if (fields.size() >= 4) {
            DataPoint point;
            point.timestamp = QDateTime::fromString(fields[0], "yyyy-MM-dd hh:mm:ss");
            point.value = fields[1].toDouble();
            point.label = fields[2];
            point.category = fields[3].toInt();
            
            dataPoints->append(point);
        }
    }
    
    file.close();
    
    // 更新图表
    updateChartSeries(chartType);
    
    return true;
}

void DataVisualization::createDataTables()
{
    // 这里可以实现创建数据库表的逻辑
    // 如果使用SQLite或其他数据库存储历史数据
    // 此处简化实现，实际应用中可能需要更复杂的数据库操作
}

// C风格的辅助函数实现
extern "C" {
    const char* chartTypeToString(ChartType type)
    {
        switch (type) {
            case CHART_FLOW_RATE:
                return "流量图表";
            case CHART_BATTERY_LEVEL:
                return "电池电量图表";
            case CHART_SAMPLING_STATS:
                return "采样统计图表";
            case CHART_DEVICE_STATUS:
                return "设备状态图表";
            case CHART_TEMPERATURE:
                return "温度图表";
            case CHART_HUMIDITY:
                return "湿度图表";
            default:
                return "未知图表";
        }
    }
    
    double calculateAverage(const DataPoint* points, int count)
    {
        if (count <= 0 || !points) return 0.0;
        
        double sum = 0.0;
        for (int i = 0; i < count; ++i) {
            sum += points[i].value;
        }
        
        return sum / count;
    }
    
    double calculateMaxValue(const DataPoint* points, int count)
    {
        if (count <= 0 || !points) return 0.0;
        
        double maxValue = points[0].value;
        for (int i = 1; i < count; ++i) {
            if (points[i].value > maxValue) {
                maxValue = points[i].value;
            }
        }
        
        return maxValue;
    }
    
    double calculateMinValue(const DataPoint* points, int count)
    {
        if (count <= 0 || !points) return 0.0;
        
        double minValue = points[0].value;
        for (int i = 1; i < count; ++i) {
            if (points[i].value < minValue) {
                minValue = points[i].value;
            }
        }
        
        return minValue;
    }
    
    int filterDataPointsByTime(const DataPoint* input, DataPoint* output, 
                              int inputCount, const QDateTime* startTime, const QDateTime* endTime)
    {
        if (!input || !output || !startTime || !endTime || inputCount <= 0) return 0;
        
        int outputCount = 0;
        for (int i = 0; i < inputCount; ++i) {
            if (input[i].timestamp >= *startTime && input[i].timestamp <= *endTime) {
                output[outputCount++] = input[i];
            }
        }
        
        return outputCount;
    }
}
